package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.BankCardInfo;
import cn.lijinquan.p2p.entites.ProductAccount;
import cn.lijinquan.p2p.entites.ResultMap;
import cn.lijinquan.p2p.entites.UserAcount;
import com.lijinquan.springcloud.constants.FrontStatusConstants;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Map;

/**
 * Created by lijinquan on 2019/10/5.
 */
@RestController
public class ChargesControllerConsumer {

    private static final String REST_URL_PREFIX = "http://P2P-WEB/";
    @Autowired
    private RestTemplate restTemplate;


    @RequestMapping("/charges/charge")
    public ResultMap<Boolean> charge(HttpServletRequest request) {
        ResultMap<Boolean> rm = new ResultMap<>();
        String chargeBank = request.getParameter("chargeBank");
        String chargeMoney = request.getParameter("chargeMoney");
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        BankCardInfo bu = restTemplate.getForObject(REST_URL_PREFIX + "/bankCardInfo/findBankInfoByUsername/" + tokenmap.get("id"), BankCardInfo.class);
        Boolean b = doCharge(bu.getBankCardNum(), Double.valueOf(chargeMoney));
        rm.setBody(b);
        if (!b) {// 余额不足或者其他
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }

        // 到这了说明可以充值 ， 修改userAcount表中的总额和可用余额
        // 1. 获取到该用户的userAcount 记录
        UserAcount ua = restTemplate.getForObject(REST_URL_PREFIX + "/account/accountHomepage/" + tokenmap.get("id"), UserAcount.class);
        ua.setTotal(ua.getTotal().add(new BigDecimal(chargeMoney)));
        ua.setBalance(ua.getBalance().add(new BigDecimal(chargeMoney)));
        Boolean modifyRes = restTemplate.postForObject(REST_URL_PREFIX + "/account/modifyUserAcount", ua, Boolean.class);
        rm.setBody(modifyRes);
        if (!modifyRes) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        return rm;
    }

    public Boolean doCharge(String bankId, Double money) {
        //创建动态客户端
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        Client client = factory.createClient("http://localhost:8090/demo/api?wsdl");
        // 需要密码的情况需要加上用户名和密码
        //client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,PASS_WORD));
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        httpClientPolicy.setConnectionTimeout(2000);  //连接超时
        httpClientPolicy.setAllowChunking(false);    //取消块编码
        httpClientPolicy.setReceiveTimeout(120000);     //响应超时
        conduit.setClient(httpClientPolicy);
        //client.getOutInterceptors().addAll(interceptors);//设置拦截器
        try {
            Object[] objects = new Object[0];
            // invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke("charge", bankId, money);
            System.out.println("充值结果：" + objects[0]);
            return (boolean) objects[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    @RequestMapping("/extracts/extractMoney")
    public ResultMap<Boolean> extractMoney() {

        ResultMap<Boolean> rm = new ResultMap<>();

        return rm;
    }

    /**
     * 购买理财产品
     * @param request
     * @param productAccount
     * @return
     */
    @PostMapping("/charges/addMayTake")
    public ResultMap<Boolean> addMayTake(HttpServletRequest request, @RequestBody ProductAccount productAccount) {
        ResultMap<Boolean> rm = new ResultMap<>();
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        Boolean result=false;
        productAccount.setpUid((Integer) tokenmap.get("id"));
        productAccount.setUsername((String) tokenmap.get("userName"));
        try {
            result= restTemplate.postForObject(REST_URL_PREFIX + "/charges/addMayTake" ,productAccount, Boolean.class);

        }catch (Exception e){
            e.printStackTrace();
        }
        rm.setBody(result);
        if(!result){
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
        }
        return rm;

    }

    /**
     * 投资管理-我的投资-购买中的计划
     * @return
     */
    @RequestMapping("/charges/ProductAccountBuying")
    public ResultMap<Map<String,Object>>  ProductAccountBuying(HttpServletRequest request){
        ResultMap<Map<String,Object> > rm=new ResultMap<>();
        String currentPage = request.getParameter("currentPage");
        Map<String,Object> m = restTemplate.getForObject(REST_URL_PREFIX + "/charges/ProductAccountBuying/"+currentPage, Map.class);
        rm.setBody(m);
        return rm;
    }


}
